package com.sqlcheck.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqlcheck.common.Result;
import com.sqlcheck.dto.request.BatchUpdateRuleStatusRequest;
import com.sqlcheck.dto.request.CreateCompatibilityRuleRequest;
import com.sqlcheck.dto.request.UpdateCompatibilityRuleRequest;
import com.sqlcheck.dto.response.CompatibilityRuleResponse;
import com.sqlcheck.service.CompatibilityRuleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/compatibility-rules")
@RequiredArgsConstructor
@Tag(name = "兼容性规则管理", description = "查看和管理SQL兼容性检查规则")
public class CompatibilityRuleController {

        private final CompatibilityRuleService ruleService;

        @GetMapping
        @Operation(summary = "分页获取兼容性规则", description = "支持按数据库类型、严重程度、分类等条件筛选")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = IPage.class))),
                        @ApiResponse(responseCode = "400", description = "请求参数无效"),
                        @ApiResponse(responseCode = "500", description = "服务器内部错误")
        })
        public Result<IPage<CompatibilityRuleResponse>> getRules(
                        @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer current,
                        @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
                        @Parameter(description = "源数据库类型", example = "ORACLE") @RequestParam(required = false) String sourceDbType,
                        @Parameter(description = "目标数据库类型", example = "GOLDENDB") @RequestParam(required = false) String targetDbType,
                        @Parameter(description = "严重程度", example = "HIGH") @RequestParam(required = false) String severity,
                        @Parameter(description = "规则分类", example = "DATA_TYPE") @RequestParam(required = false) String category,
                        @Parameter(description = "搜索关键词", example = "CHAR") @RequestParam(required = false) String search) {

                log.info("查询兼容性规则: current={}, size={}, sourceDbType={}, targetDbType={}, severity={}, category={}, search={}",
                                current, size, sourceDbType, targetDbType, severity, category, search);

                Page<CompatibilityRuleResponse> page = new Page<>(current, size);
                IPage<CompatibilityRuleResponse> rules = ruleService.getRules(page, sourceDbType, targetDbType,
                                severity,
                                category, search);

                return Result.success(rules);
        }

        @GetMapping("/{ruleId}")
        @Operation(summary = "获取规则详情", description = "根据规则ID获取详细信息")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = CompatibilityRuleResponse.class))),
                        @ApiResponse(responseCode = "404", description = "规则不存在")
        })
        public Result<CompatibilityRuleResponse> getRuleById(
                        @Parameter(description = "规则ID", required = true, example = "1") @PathVariable Long ruleId) {

                log.info("获取规则详情: ruleId={}", ruleId);
                CompatibilityRuleResponse rule = ruleService.getRuleById(ruleId);
                return Result.success(rule);
        }

        @GetMapping("/by-rule-id/{ruleId}")
        @Operation(summary = "根据规则编号获取规则详情", description = "根据规则编号(如OR_SYNTAX_001)获取详细信息")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = CompatibilityRuleResponse.class))),
                        @ApiResponse(responseCode = "404", description = "规则不存在")
        })
        public Result<CompatibilityRuleResponse> getRuleByRuleId(
                        @Parameter(description = "规则编号", required = true, example = "OR_SYNTAX_001") @PathVariable String ruleId) {

                log.info("根据规则编号获取规则详情: ruleId={}", ruleId);
                CompatibilityRuleResponse rule = ruleService.getRuleByRuleId(ruleId);
                return Result.success(rule);
        }

        @PostMapping
        // @PreAuthorize("hasRole('ADMIN')") // 暂时注释掉权限控制
        @Operation(summary = "创建新规则", description = "创建新的兼容性规则（仅管理员）")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = CompatibilityRuleResponse.class))),
                        @ApiResponse(responseCode = "400", description = "请求参数无效"),
                        @ApiResponse(responseCode = "403", description = "权限不足"),
                        @ApiResponse(responseCode = "409", description = "规则ID已存在")
        })
        public Result<CompatibilityRuleResponse> createRule(
                        @Valid @RequestBody @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "创建规则请求", required = true, content = @Content(schema = @Schema(implementation = CreateCompatibilityRuleRequest.class))) CreateCompatibilityRuleRequest request) {

                log.info("创建兼容性规则: ruleId={}, ruleName={}", request.getRuleId(), request.getRuleName());
                CompatibilityRuleResponse rule = ruleService.createRule(request);
                return Result.success(rule);
        }

        @PutMapping("/{ruleId}")
        // @PreAuthorize("hasRole('ADMIN')") // 暂时注释掉权限控制
        @Operation(summary = "更新规则", description = "更新兼容性规则信息（仅管理员）")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = CompatibilityRuleResponse.class))),
                        @ApiResponse(responseCode = "400", description = "请求参数无效"),
                        @ApiResponse(responseCode = "403", description = "权限不足"),
                        @ApiResponse(responseCode = "404", description = "规则不存在")
        })
        public Result<CompatibilityRuleResponse> updateRule(
                        @Parameter(description = "规则ID", required = true, example = "1") @PathVariable Long ruleId,
                        @Valid @RequestBody @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "更新规则请求", required = true, content = @Content(schema = @Schema(implementation = UpdateCompatibilityRuleRequest.class))) UpdateCompatibilityRuleRequest request) {

                log.info("更新兼容性规则: ruleId={}, ruleName={}", ruleId, request.getRuleName());
                CompatibilityRuleResponse rule = ruleService.updateRule(ruleId, request);
                return Result.success(rule);
        }

        @PutMapping("/{ruleId}/status")
        // @PreAuthorize("hasRole('ADMIN')") // 暂时注释掉权限控制
        @Operation(summary = "切换规则状态", description = "切换规则启用/禁用状态（仅管理员）")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "状态切换成功", content = @Content(schema = @Schema(implementation = CompatibilityRuleResponse.class))),
                        @ApiResponse(responseCode = "403", description = "权限不足"),
                        @ApiResponse(responseCode = "404", description = "规则不存在")
        })
        public Result<CompatibilityRuleResponse> toggleRuleStatus(
                        @Parameter(description = "规则ID", required = true, example = "1") @PathVariable Long ruleId) {

                log.info("切换规则状态: ruleId={}", ruleId);
                CompatibilityRuleResponse rule = ruleService.toggleRuleStatus(ruleId);
                return Result.success(rule);
        }

        @DeleteMapping("/{ruleId}")
        // @PreAuthorize("hasRole('ADMIN')") // 暂时注释掉权限控制
        @Operation(summary = "删除规则", description = "删除兼容性规则（软删除，仅管理员）")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "删除成功"),
                        @ApiResponse(responseCode = "403", description = "权限不足"),
                        @ApiResponse(responseCode = "404", description = "规则不存在")
        })
        public Result<Void> deleteRule(
                        @Parameter(description = "规则ID", required = true, example = "1") @PathVariable Long ruleId) {

                log.info("删除兼容性规则: ruleId={}", ruleId);
                ruleService.deleteRule(ruleId);
                return Result.success();
        }

        @PostMapping("/batch-status")
        // @PreAuthorize("hasRole('ADMIN')") // 暂时注释掉权限控制
        @Operation(summary = "批量更新规则状态", description = "批量启用或禁用规则（仅管理员）")
        @ApiResponses({
                        @ApiResponse(responseCode = "200", description = "批量更新成功"),
                        @ApiResponse(responseCode = "400", description = "请求参数无效"),
                        @ApiResponse(responseCode = "403", description = "权限不足")
        })
        public Result<Void> batchUpdateRuleStatus(
                        @Valid @RequestBody @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "批量状态更新请求", required = true, content = @Content(schema = @Schema(implementation = BatchUpdateRuleStatusRequest.class))) BatchUpdateRuleStatusRequest request) {

                log.info("批量更新规则状态: ruleIds={}, isActive={}", request.getRuleIds(), request.getIsActive());
                ruleService.batchUpdateRuleStatus(request.getRuleIds(), request.getIsActive());
                return Result.success();
        }
}
